const DEBUGGER = false;
const AUTHORIZER_APPID = 'wx36bea992a3856d4a'; // mofa
// var AUTHORIZER_APPID = 'wx022ec8687b780a34'; // panx
const SDK_CONFIG_API = '/open-wechat/authorizer-js-sdk/';
const MAY_PROMO_CREATE = '/api/may-promo/create';
const GET_MEDIA_ID = '/api/may-promo/get-media-id';
const GET_PIC_URL = '/api/may-promo/get-pic-url'; // 请求化妆后的url

/* global mayPromoMixin, Vue, weui, axios, VConsole, panxVConsole, wx */
function initTryOn() {
	return new Vue({
		el: '#root',

		mixins: [mayPromoMixin],

		data() {
			return {
				openid: null, // openid
				user_info: null, // 用户数据
				current_media_id: null, // 媒体文件的 id;
				cosmetics: [], // 化妆素材,
				tencent_image: null,
				selected_cosmetic_id: null,
				can_lucky_draw: false, // 抽奖?
				page_title: '2D 美妆试妆',
				share_title: '魔镜魔镜告诉我',
				page_icon: 'https://gz.bcebos.com/v1/beauty-mirror/may-promo/icon.png',
				is_visible_cover: true,
				is_show_share_tip: false, // false
				is_visible_error: false,
				error_tips: '试妆失败,请重新上传照片',
				picture_cache: { // 图像缓存

				},
			};
		},

		mounted() {
			const self = this;

			panxVConsole({ left: '0px', bottom: '0px' });

			this.resolveOpenId()
				.then((openid) => {
					self.openid = openid;
					// 请求用户信息
					self.fetchUserInfo(openid)
						.then((userInfo) => {
							if (userInfo) {
								self.user_info = userInfo;
							}
						});

					self.fetchSdkConfig(AUTHORIZER_APPID);
					self.fetchCosmetics({ openid, appid: AUTHORIZER_APPID });
					self.handleFetchCouponIndex(openid);
				});
		},

		methods: {

			/**
       * 请求sdk 配置
       */
			fetchSdkConfig() {
				const self = this;

				const sdkParams = {
					target_url: window.location.href,
				};

				if (DEBUGGER) {
					sdkParams.debug = 1;
				}

				axios.post(SDK_CONFIG_API + AUTHORIZER_APPID, sdkParams)
					.then((response) => {
						if (response.data.code !== 0) {
							throw new Error(response.data.error);
						} else {
							self.initWxSdk(response.data.config);
						}
					})
					.catch((error) => {
						console.error(error);
					});
			},

			/**
       * 初始化 wechat skd
       */
			initWxSdk(config) {
				// alert(config.signature);
				console.warn('init sdk', config);

				wx.config(config);
				this.listenWechatSdkEvent();
			},

			/**
       * 监听 wechat sdk
       */
			listenWechatSdkEvent() {
				wx.ready(this.handleWxSdkReady);
				wx.error(this.handleWxSdkError);

				// 分享朋友圈
				wx.onMenuShareTimeline({
					title: this.share_title, // 分享标题
					link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: this.page_icon, // 分享图标
					success: this.handleShareTimeLineSuccess,
					cancel: this.handleShareTimeLineCancel,
					trigger: this.logMenuEvent,
				});
			},

			logMenuEvent(event) {
				console.error(event);
			},

			/**
       * 处理sdk 错误
       * @param res
       */
			handleWxSdkError(res) {
				console.error(res);
			},

			/**
       * 处理 wx ready
       */
			handleWxSdkReady() {
				// alert('ready');
			},

			/**
       * 分类朋友圈
       */
			handleShareTimeLineSuccess() {
				window.location.href = `/may-promo/makeup-tryon/shake.html?v=${Math.random()}`;
			},

			/**
       *  取消分享朋友圈
       */
			handleShareTimeLineCancel() {
				weui.alert('只有分享才能抽奖');
			},


			/**
       * 请求美妆素材
       * @params {string} params.openid
       * @params {string} params.appid
       */
			fetchCosmetics(params) {
				const self = this;
				axios.get(MAY_PROMO_CREATE, { params })
					.then((response) => {
						if (response.data.code !== 0) {
							throw new Error(response.data.error);
						} else {
							self.cosmetics = response.data.cosmetics;
							return response.data.cosmetics;
						}
					})
					.then((cosmetics) => {
						if (cosmetics.length) { // 设置默认
							self.selected_cosmetic_id = cosmetics[0].id;
						}
					})
					.catch((error) => {
						console.error(error);
					});
			},

			/**
       *  处理图像文件 change
       */
			selectImageFile() {
				const self = this;
				wx.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success(res) {
						const { localIds } = res; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
						console.error('res', res);
						self.uploadImage(localIds[0]);
					},
				});
			},

			/**
       * 上传 wx 图像
       */
			uploadImage(localId) {
				const self = this;
				wx.uploadImage({
					localId, // 需要上传的图片的本地ID，由chooseImage接口获得
					isShowProgressTips: 1, // 默认为1，显示进度提示
					success(res) {
						const { serverId } = res; // 返回图片的服务器端ID
						self.current_media_id = serverId;
						self.fetchTencentPictureUrl({
							appid: AUTHORIZER_APPID,
							openid: self.openid,
							media_id: serverId,
							id: self.selected_cosmetic_id,
							// type: 'png'
						});
					},
				});
			},

			/**
       * 创建 formData 对象
       */
			createDataForm(form) {
				const fd = new FormData();

				Object.keys(form).forEach(field => fd.append(field, form[field]));

				return fd;
			},

			/**
       * 提交图像并换取图像的id
       */
			postImageFile(form) {
				const self = this;
				axios.post(GET_MEDIA_ID, form)
					.then((response) => {
						self.current_media_id = response.data.media_id;
						return response.data.media_id;
					})
					.then((mediaId) => {
						self.fetchTencentPictureUrl({
							appid: AUTHORIZER_APPID,
							openid: self.openid,
							media_id: mediaId,
							id: self.selected_cosmetic_id,
							// type: 'png'
						});
					})
					.catch((error) => {
						console.error(error);
					});
			},

			/**
       *  请求化妆后的url
       */
			fetchTencentPictureUrl(params) {
				const loading = weui.loading('马上好了');
				const self = this;
				const key = `${params.media_id}#${params.id}`;
				const cache = this.getPictureFromCache(key);
				if (cache) {
					this.tencent_image = cache;
					loading.hide();
					return;
				}

				axios.get(GET_PIC_URL, { params })
					.then((response) => {
						if (response.data.code !== 0) { //
							throw new Error(response.data.error);
						} else {
							const { ret } = response.data.tencent_image;
							if (ret !== 0) { // Tencent error
								const { msg } = response.data.tencent_image;
								console.warn(msg);

								const errorTip = (ret === 16402) ? '照片中找不到脸部,请重新上传' : (`头像图片分析失败[${ret}]`);
								throw new Error(errorTip);
							} else {
								const base64 = `data:image/jpeg;base64,${response.data.tencent_image.data.image}`;
								self.tencent_image = base64;
								self.hideCover();
								self.setPictureToCache(key, base64);
							}
						}
					})
					.catch((error) => {
						self.showErrorTips(error.message);
						console.error(error);
					})
					.then(() => {
						loading.hide();
					});
			},

			/**
       * 获取图片
       * @param key
       * @returns {*}
       */
			getPictureFromCache(key) {
				if (key in this.picture_cache) {
					return this.picture_cache[key];
				}
				return null;
			},

			/**
       * 设置缓存
       * @param key
       * @param value
       */
			setPictureToCache(key, value) {
				/**
         * 康林你需要仔细学习下操作符优先级
         *
         * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
         */
				if (!(key in this.picture_cache)) {
					this.picture_cache[key] = value;
				}
			},

			/**
       * 显示错误
       */
			showErrorTips(message, timer) {
				if (this.is_visible_error) {
					return;
				}
				const timeout = timer || 1500;
				const self = this;
				this.error_tips = message;
				this.is_visible_error = true;
				window.setTimeout(() => {
					self.is_visible_error = false;
				}, timeout);
			},

			/**
       *  处理 素材 select
       */
			handleCosmeticsSelected(id) {
				this.selected_cosmetic_id = id;
				if (!this.current_media_id) return;
				this.fetchTencentPictureUrl({
					appid: AUTHORIZER_APPID,
					openid: this.openid,
					media_id: this.current_media_id,
					id: this.selected_cosmetic_id,
					// type: 'png'
				});
			},

			/**
       *  隐藏封面
       */
			hideCover() {
				this.is_visible_cover = false;
			},

			/**
       *  隐藏分享提示
       */
			hideShareTips() {
				this.is_show_share_tip = false;
			},

			/**
       * 请求卡券列表
       * @param openid
       */
			handleFetchCouponIndex(openid) {
				const self = this;
				this.fetchCouponIndex({
					appid: AUTHORIZER_APPID,
					openid,
				}).then((coupons) => {
					if (coupons instanceof Array && coupons.length > 0) {
						self.hideShareTips();
					} else {
						self.is_show_share_tip = true;
					}
				});
			},

			initVConsole() {
				return new VConsole();
			},
		},
	});
}

initTryOn();
